package com.glsc.ngateway.platform.controller.it;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItCloudDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItServerDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItVirtualDevice;
import com.glsc.ngateway.platform.service.it.CloudService;
import com.glsc.ngateway.platform.service.it.SequenceService;
import com.glsc.ngateway.platform.service.it.ServerService;
import com.glsc.ngateway.platform.service.it.VirtualService;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/it/oacall")
public class OaCallController {
    private static final Logger logger = LoggerFactory.getLogger(OaCallController.class);
    @Autowired
    private VirtualService virtualService;
    @Autowired
    private ServerService serverService;
    @Autowired
    private CloudService cloudService;
    @Autowired
    private SequenceService sequenceService;

    @RequestMapping(method = RequestMethod.POST, value = "process")
    public String oaProcess(@RequestBody String jsonObjectInput) throws Exception {
        logger.info("oa回调资产管理系统接口报文:" + jsonObjectInput);
        JSONObject jsonObject = (JSONObject) JSON.parse(jsonObjectInput);
        Map<String, Object> inputMap = Maps.newHashMap();
        Map<String, Object> inputMap1 = Maps.newHashMap();

        if ("1".equals((jsonObject.getString("LCMC")))) {
            ItServerDevice itServerDevice = new ItServerDevice();
            itServerDevice.setBusinessName((String) jsonObject.get("business_name"));//业务系统
            itServerDevice.setNetworkSegment(convert2String(jsonObject.get("YWWD"))); //业务网段
            itServerDevice.setApplicationDetail((String) jsonObject.get("application_detail"));//应用明细(同mx_id)
            itServerDevice.setMachineRoom(convert2String(jsonObject.get("machine_room")));//机房
            itServerDevice.setMachineCab((String) jsonObject.get("machine_cab")); //机柜
            itServerDevice.setMachineUnit((String) jsonObject.get("machine_unit"));//单位
            itServerDevice.setCapitalType((String) jsonObject.get("capital_type"));//资产编号
            itServerDevice.setCapitalStyle(convert2String(jsonObject.get("capital_style")));//设备类型
            itServerDevice.setBrand(convert2String(jsonObject.get("brand"))); //品牌
            itServerDevice.setBrandType((String) jsonObject.get("SBXH"));//设备型号
            itServerDevice.setPnPid((String) jsonObject.get("pn_pid"));//PN/PID
            itServerDevice.setOperationSys(convert2String(jsonObject.get("operation_sys")));//操作系统
            itServerDevice.setDiskType((String) jsonObject.get("disk_type"));//硬盘规格
            itServerDevice.setCpu((String) jsonObject.get("cpu"));
            itServerDevice.setMemory((String) jsonObject.get("memory"));
            itServerDevice.setIlo((String) jsonObject.get("ILO"));
            itServerDevice.setUserId((String) jsonObject.get("SQR"));//责任人
            itServerDevice.setCcTime(convertTime(jsonObject.get("cc_time")));//出厂年份
            itServerDevice.setWbTime(convertTime(jsonObject.get("wb_time")));//维保年份
            itServerDevice.setSjTime(convertTime(jsonObject.get("sj_time")));//上架时间
            itServerDevice.setPlanOn((String) jsonObject.get("plan_on"));//预计使用年限
            itServerDevice.setSupportPower(convert2String(jsonObject.get("support_power")));//单/双电源
            itServerDevice.setSn((String) jsonObject.get("SN"));
            itServerDevice.setMac1((String) jsonObject.get("MAC1"));
            itServerDevice.setMac2((String) jsonObject.get("MAC2"));
            itServerDevice.setMac3((String) jsonObject.get("MAC3"));
            itServerDevice.setMac4((String) jsonObject.get("MAC4"));
            itServerDevice.setIp1((String) jsonObject.get("IP1"));
            itServerDevice.setIp2((String) jsonObject.get("IP2"));
            itServerDevice.setQj(convert2String(jsonObject.get("QJ")));//群集
            itServerDevice.setBf((String) jsonObject.get("BF"));//备份情况说明
            logger.info("新增物理机服务器");
            serverService.addOrUpdateServer(itServerDevice);          //新增物理机服务器
        } else if ("2".equals((jsonObject.getString("LCMC")))) {
            if ("201".equals(((String) jsonObject.get("ZB1")))) {
                ItVirtualDevice itVirtualDevice = new ItVirtualDevice();
               /* String devId = "VD-" + sequenceService.getNextValue("virtual_dev");
                itVirtualDevice.setDevId(devId);
                itVirtualDevice.setMark("1");*/

                itVirtualDevice.setBusinessName((String) jsonObject.get("business_name1"));//业务系统
                itVirtualDevice.setApplicationDetail((String) jsonObject.get("application_detail1")); //应用明细(同mx_id)
                itVirtualDevice.setNetworkSegment(convert2String(jsonObject.get("YWWD")));//业务网段
                itVirtualDevice.setVirtualName((String) jsonObject.get("virtual_name"));//虚拟机名称
                itVirtualDevice.setOperationSys(convert2String(jsonObject.get("operation_sys1")));//操作系统
                itVirtualDevice.setMachineArea(convert2String(jsonObject.get("HJ")));//环境
                itVirtualDevice.setVcentIp((String) jsonObject.get("vcent_ip")); //Vcent_ip
                itVirtualDevice.setVirtualIp(convertInteger(jsonObject.get("virtual_ip"))); //虚拟主机IP,关联服务器IP1
                itVirtualDevice.setQj((String) jsonObject.get("qj"));//群集
                itVirtualDevice.setCpu(convert2String(jsonObject.get("cpu1")));
                itVirtualDevice.setMemory(convert2String(jsonObject.get("memory1")));
                itVirtualDevice.setUserId((String) jsonObject.get("SQR"));//责任人
                itVirtualDevice.setBz((String) jsonObject.get("QT")); //备注
                itVirtualDevice.setIp1((String) jsonObject.get("IP1"));
                itVirtualDevice.setMac1((String) jsonObject.get("MAC1"));
                itVirtualDevice.setIp2((String) jsonObject.get("IP2"));
                itVirtualDevice.setMac2((String) jsonObject.get("MAC2"));
                itVirtualDevice.setBf((String) jsonObject.get("BF"));//备份情况说明
                logger.info("新增虚拟机服务器");
                virtualService.addOrUpdateVirtual(itVirtualDevice);            //新增虚拟机服务器
            }
            if ("202".equals((jsonObject.getString("ZB2")))) {
                ItCloudDevice itCloudDevice = new ItCloudDevice();
                /*String devId = "CS-" + sequenceService.getNextValue("cloud_dev");
                itCloudDevice.setDevId(devId);
                itCloudDevice.setMark("1");*/

                itCloudDevice.setCloudId(convert2String(jsonObject.get("cloud_id")));//云平台ID
                itCloudDevice.setCloudStyle(convert2String(jsonObject.get("cloud_style")));//类型
                itCloudDevice.setCloudArea(convertInteger(jsonObject.get("cloud_area")));//区域
                itCloudDevice.setInsideIp((String) jsonObject.get("inside_ip"));//内网IP
                itCloudDevice.setEip((String) jsonObject.get("eip"));//EIP
                itCloudDevice.setSlb((String) jsonObject.get("slb"));//SLB
                itCloudDevice.setOperationSys(convert2String(jsonObject.get("operation_sys"))); //操作系统
                itCloudDevice.setCpu(convert2String(jsonObject.get("cpu")));
                itCloudDevice.setMemory(convert2String(jsonObject.get("memory")));
                itCloudDevice.setManageControl((String) jsonObject.get("manage_control"));//管理控制台
                itCloudDevice.setMasterName((String) jsonObject.get("master_name"));//主机名
                itCloudDevice.setUserId((String) jsonObject.get("SQR"));//责任人
                itCloudDevice.setBusinessName(convert2String(jsonObject.get("business_name")));
                logger.info("新增云主机服务器");
                cloudService.addOrUpdateCloud(itCloudDevice);            //新增云主机服务器
            }
        } else if ("3".equals((jsonObject.getString("LCMC")))) {
            if (jsonObject.getString("DEV_ID").startsWith("CS")) {
                //删除
                String devId = (String) jsonObject.get("DEV_ID");
                cloudService.deleteCloud(devId);//云平台下架
                logger.info("云平台下架"+devId);
            } else if (jsonObject.getString("DEV_ID").startsWith("VD")) {
                String devId = (String) jsonObject.get("DEV_ID");
                virtualService.deleteVirtual(devId);    //虚拟机下架
                logger.info("虚拟机下架"+devId);
            } else {
//                inputMap.put("dev_id", jsonObject.get("DEV_ID"));
//                inputMap.put("ip1", jsonObject.get("IP1"));
//                inputMap.put("machine_status", "116");

                String devId = (String) jsonObject.get("DEV_ID");
                String ip1 = (String) jsonObject.get("IP1");
                ItServerDevice dev = serverService.findByDevId(devId);
                if (dev != null) {
                    ItServerDevice temp = new ItServerDevice();
                    BeanUtils.copyProperties(dev,temp);
                    temp.setIp1(ip1);
                    temp.setMachineStatus("116");
                    serverService.addOrUpdateServer(temp);//物理机下架
                    logger.info("物理机下架");
                }
            }
        } else if ("4".equals((jsonObject.getString("LCMC")))) {

            if (jsonObject.getString("DEV_ID").startsWith("CS")) {
                String devId = (String) jsonObject.get("DEV_ID");
                ItCloudDevice dev = cloudService.findByDevId(devId);
                if (dev != null) {
                    dev.setOperationSys(convert2String(jsonObject.get("operation_sys3")));//操作系统
                    dev.setCpu(convert2String(jsonObject.get("cpu3")));
                    dev.setMemory(convert2String(jsonObject.get("memory3")));
                    dev.setApplication((String) jsonObject.get("application"));//应用
                    dev.setUserId((String) jsonObject.get("SQR"));//责任人
                    String businessName = convert2String(jsonObject.get("business_name"));
                    if(StringUtils.isNotBlank(businessName)){
                        dev.setBusinessName(businessName);
                    }
                    cloudService.addOrUpdateCloud(dev);//云平台变更
                    logger.info("云平台变更");
                }
            } else if (jsonObject.getString("DEV_ID").startsWith("VD")) {
                String devId = (String) jsonObject.get("DEV_ID");
                ItVirtualDevice dev = virtualService.findByDevId(devId);
                if (dev != null) {
                    //避免jpa自动保存
                    ItVirtualDevice temp = new ItVirtualDevice();
                    BeanUtils.copyProperties(dev,temp);
                    temp.setBusinessName((String) jsonObject.get("business_name2")); //业务系统
                    temp.setOperationSys(convert2String(jsonObject.get("operation_sys2")));//操作系统
                    temp.setCpu(convert2String(jsonObject.get("cpu2")));
                    temp.setMemory(convert2String(jsonObject.get("memory2")));
                    temp.setIp1((String) jsonObject.get("XNJNEWIP"));
                    temp.setUserId((String) jsonObject.get("SQR"));//责任人
                    temp.setMachineArea(convert2String(jsonObject.get("machine_area"))); //环境
                    temp.setApplicationDetail((String) jsonObject.get("application_detail2"));//应用明细(同mx_id)
                    virtualService.addOrUpdateVirtual(temp); //虚拟机变更
                    logger.info("虚拟机变更");
                }
            } else {
                String devId = (String) jsonObject.get("DEV_ID");
                ItServerDevice dev = serverService.findByDevId(devId);
                if (dev != null) {
                    //避免jpa自动保存
                    ItServerDevice temp = new ItServerDevice();
                    BeanUtils.copyProperties(dev,temp);
                    temp.setBusinessName((String) jsonObject.get("business_name"));//业务系统
                    temp.setOperationSys(convert2String(jsonObject.get("operation_sys")));//操作系统
                    temp.setApplicationDetail((String) jsonObject.get("application_detail")); //应用明细(同mx_id)
                    temp.setIp1((String) jsonObject.get("NEWIP"));
                    temp.setCpu((String) jsonObject.get("cpu"));
                    temp.setMemory((String) jsonObject.get("memory"));
                    temp.setUserId((String) jsonObject.get("SQR"));//责任人
                    serverService.addOrUpdateServer(temp); //服务器变更
                    logger.info("服务器变更");
                }
            }
        }

        return null;
    }

    private LocalDateTime convertTime(Object object) {
        if (object == null || StringUtils.isEmpty(object.toString())){
            return null;
        } else {
            LocalDate date = DateUtil.getLocalDate(object.toString());
            LocalDateTime localDateTime = date.atTime(0,0,0);
            return localDateTime;
        }
    }

    private Integer convertInteger(Object object) {
        if (object == null || StringUtils.isEmpty(object.toString())){
            return null;
        } else {
            return Integer.valueOf(object.toString());
        }
    }
    private String convert2String(Object object) {
        if (object == null || StringUtils.isEmpty(object.toString())){
            return null;
        } else {
            return object.toString();
        }
    }
    @RequestMapping(method = RequestMethod.POST, value = "test")
    public String test(@RequestBody String jsonObjectInput) throws Exception {
        return jsonObjectInput;
    }
}
